/*
 * CreationState.cpp
 *
 *  Created on: 11-01-2011
 *      Author: Przemek
 */

#include "world/creation/CreationState.hpp"
#include "world/World.hpp"
using namespace boost;

void CreationState::clearCreateTool()
{
	createTool.reset();
	toAdd.reset();
}

void CreationState::setCreateTool(CreateToolState* createTool)
{
	this->createTool = shared_ptr<CreateToolState> (createTool);
	toAdd = shared_ptr<Element> (createTool->createAtPoint(Vector()));
}

bool CreationState::anyCreateTool() const
{
	return (getCreateTool() != 0);
}

const CreateToolState* CreationState::getCreateTool() const
{
	return createTool.get();
}

void CreationState::moveCenteredTo(const Vector& point)
{
	const Vector& size = toAdd->getSize().toVector();
	toAdd->setPosition(point - size / 2.0f);
}

void CreationState::moveAnchoredToGrid(const Vector& point)
{
	toAdd->setPosition(getAnchoredToGrid(point));
}

bool CreationState::anyToAdd() const
{
	return (toAdd.get() != 0);
}

void CreationState::tryAddElementToWorld()
{
	World& world = World::getInstance();
	if(world.canPlaceAt(toAdd->getBounds()))
	{
		world.add(toAdd);
		resetToAdd();
	}
}

void CreationState::resetToAdd()
{
	if(anyCreateTool())
	{
		const Vector& previousPoint = toAdd->getPosition();
		toAdd = shared_ptr<Element> (getCreateTool()->createAtPoint(previousPoint));
	}
}

Element* CreationState::getToAdd()
{
	return toAdd.get();
}

Vector CreationState::getAnchoredToGrid(const Vector& point) const
{
	const int size = static_cast<int> (toAdd->getSize().getWidth());
	const int gridX = static_cast<int> (point.getX() / size);
	const int gridY = static_cast<int> (point.getY() / size);

	return Vector(gridX * size, gridY * size);
}
